<?php

namespace app\index\controller;


use app\index\model\Brand;
use app\index\model\GoodsImg;
use app\index\model\ShopCart;
use app\index\model\Type;
use think\Controller;
use think\Db;
use think\Validate;
use think\Loader;
use think\View;


class Index extends Controller
{

    /**
     * 主页
     * @return mixed
     */
    public function index()
    {


        $shopCart = ShopCart::where('user_id', session('uid'))
            ->select();

        View::share('shopCart', $shopCart);


        //获取分类
        $result = Db('type')
            ->where("pid=0")
            ->limit(2)
            ->select();
        $type = $this->getType($result);
        View::share('type', $type);


        //获取品牌
        $brand = Brand::limit(9)
            ->select();

        //获取列表分类
        $list_result = Db('type')
            ->where("pid=0")
            ->limit(2)
            ->select();
        $list_type = $this->getType($list_result);
//         return dd($list_type);


        //新品上线
        $new_goods = \app\index\model\Goods::limit(5)
            ->where('attr_status', 2)
            ->order('time desc')
            ->join('attribute','goods.id=attribute.goods_id')
            ->group('goods.id')
            ->select();

//        return jj($new_goods);
        //疯狂抢购
        $panicbuy = \app\index\model\Goods::limit(5)
            ->where('attr_status', 1)
            ->order('time desc')
            ->join('attribute','goods.id=attribute.goods_id')
            ->group('goods.id')
            ->select();

        //热卖
        $hot_goods = \app\index\model\Goods::limit(5)
            ->where('attr_status', 3)
            ->order('time desc')
            ->join('attribute','goods.id=attribute.goods_id')
            ->group('goods.id')
            ->select();

        //推荐商品
        $recommend_goods = \app\index\model\Goods::limit(5)
            ->where('attr_status', 4)
            ->order('time desc')
            ->join('attribute','goods.id=attribute.goods_id')
            ->group('goods.id')
            ->select();

        //猜你喜欢
        $like_goods = \app\index\model\Goods::limit(5)
            ->where('attr_status', 5)
            ->order('time desc')
            ->join('attribute','goods.id=attribute.goods_id')
            ->group('goods.id')
            ->select();
//        return jj($list_type);


        $event = \think\Loader::controller('Goods', 'widget');
        $shopCart = $event->topHeader();
        $this->assign(
            [
                'brand' => $brand,
                'list_type' => $list_type,
                'new_goods' => $new_goods,
                'panicbuy' => $panicbuy,
                'hot_goods' => $hot_goods,
                'recommend_goods' => $recommend_goods,
                'like_goods' => $like_goods,
                'shopCart' => $shopCart
            ]
        );
        return $this->fetch();
    }


    /**
     * 获取分类
     * @param $type
     * @return mixed
     */
    public function getType($type)
    {
        $m = Db('type');
//        $type=$m->where("pid=0")->select();//获取一级分类
        $type2 = array();
        $type3 = array();

        foreach ($type as $key => $value) {
            $type[$key]['child'] = array();//二级分类的名字
            $type2 = $m->where("pid=" . $value['id'])->select();//获取二级分类

            foreach ($type2 as $k => $v) {

                array_push($type[$key]['child'], $v);//合并一级与二级分类
                $type[$key]['child'][$k]['child2'] = array();////三级分类的名字

                $type3 = $m->where("pid=" . $v['id'])->select();//获取三级分类
                foreach ($type3 as $v2) {
                    $v2['goods'] = \app\index\model\Goods::where('type_id', $v2['id'])->join('attribute','goods.id=attribute.goods_id')
                        ->group('goods.id')->SELECT();
                    array_push($type[$key]['child'][$k]['child2'], $v2);//合并一级二级三级分类

                }


            }

        }
        return $type;
    }

    /**
     * 登录
     * @param string $captcha
     * @return \think\response\Redirect|\think\response\View
     */
    public function login($captcha = '')
    {


        if (request()->isPost()) {
            $data['captcha'] = $captcha;
            $admin = new \app\index\model\User();
            $data = input('post.');

            // 验空
            if (isNull($data)) {
                showMsg(isNull($data));
                return view();
            }

            if ($admin->login($data) == 1) {
//                $this->error('用户不存在');

                showMsg('用户不存在');
//                $common->showMsg('用户不存在');
            } else if ($admin->login($data) == 2 || $admin->login($data) == 3) {
//                $this->error('密码错误或用户名');
                showMsg('密码错误或用户名');
//                $common->showMsg('密码错误或用户名');
            } else {
                //检查验证结果
                if (!captcha_check($data['checkcode'])) {
//                    $this->error('验证码错误');
                    showMsg('验证码错误');
                }

                return redirect('index');
            }


        }

        return view();

    }


    /**
     * 注册
     * @return \think\response\View
     */
    public function regist()
    {
        return view();
    }


    /**
     * 注册保存
     * @return \think\response\View
     */
    public function store()
    {
        //定义一个用户
        $user = [
            'user_name' => '',
            'password' => ''
        ];
        $input = input('post.');
        //判断是否有表单提交


        //validate验证
        $validate = Loader::validate('User');
        if (!$validate->scene('register')->check($input)) {
            showMsg($validate->getError());
            return view('Index/regist');
        } else {
            //判断验证码
            if (captcha_check($input['checkcode'])) {
                $result = \app\index\model\User::where('user_name', $input['username'])
                    ->find();
                if ($result) {
                    showMsg('用户已存在');
                    return view('Index/regist');
                }
                //判断2次密码是否一致
                if ($input['password'] != $input['repassword']) {
                    showMsg('俩次密码不一致');
                    return view('Index/regist');
                } else {
                    $user = new \app\index\model\User();

                    $user->user_name = $input['username'];
                    $user->password = md5($input['password']);
                    $user->save();
                    showMsg('注册成功');
                    return view('Index/login');
                }
            } else {
                showMsg('验证码错误');
                return view('Index/regist');
            }
        }

    }

    /**
     * 忘记密码----验证用户名
     */
    public function verifyUser()
    {
        if (request()->isPost()) {
            $code = input('verity-code');
            $name = input('name');
            $email = input('email');
            session('username', $name);
            $res = \app\index\model\User::where(['user_name' => $name, 'email' => $email])
                ->field('rand')
                ->find();
            if ($res && $res['rand'] == $code) {

                $this->redirect('setpwd');

            }
            $this->error('验证码错误');
        }
        return view();
    }


    /**
     * 验证用户名
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function ajaxUser()
    {

        $username = $_POST['name'];

        if ($username) {
            $name = \app\index\model\User::where('user_name', $username)->find();
            $success = isset($name) ? 1 : 0;
            echo json_encode($success, JSON_UNESCAPED_UNICODE);
        }


    }

    /**
     * 更新邮箱  发送验证码
     * @return mixed|\think\response\View
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     *
     */
    public function findpwd()
    {

        $email = $_POST['email'];
        $name = $_POST['name'];


        $title = "找回密码通知！";

        $srand = rand(11111, 99999);
        $data ['rand'] = $srand;
        $data ['email'] = $email;
        $content = "校验码:$srand";
        Db::name("user")
            ->where('user_name', $name)
            ->update($data); // 更新数据库
        if (SendMail($email, $title, $content)) {
//                    $this->success("发送成功,请到邮箱查看校验码!", url('setpwd', ['email' => $email]));
            return 1;
        } else {
            return $email->ErrorInfo;
//                    $this->error($email->ErrorInfo);
//                    die ();
        }

        //如果存在，则生成四位随机数，发到该邮箱

    }


    /**
     * 设置新密码
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function setpwd()
    {


        if (request()->isPost()) {
            $rand = input('rand');
            $name = input('name');
            $newpwd = input('pwd');
            $newpwd1 = input('password');
            if ($newpwd === $newpwd1) {
                $dbrand = Db::name("user")
                    ->where("email", session("username"))
                    ->find();

                // var_dump($dbrand);
                if ($rand != $dbrand["rand"]) {
                    $this->error("验证码错误");
                } else {
                    Db::name("user")
                        ->where("email", session("username"))
                        ->update(["password" => md5($newpwd)]);
                    $this->success('重设密码成功', "index");
                }
            } else {
                $this->error('两次密码输出不同');
            }

        }

        return $this->fetch();

    }
}
